package com.eportal.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.eportal.domain.Sysopt;

public class WebUtil {

	
	public final static String IS_BACKGROUND_USER="IS_BACKGROUND_USER";
	
	
	public final static String USER="user";
	
	/**
	 * 是否是后台用户，后台用户主要是博联智芯的内部人员，tsysuser的用户
	 * 
	 * @return 后台用户返回true，否则返回false
	 */
	public static  Boolean isBackgroudUser(){
		return (Boolean)ServletActionContext.getRequest().getSession().getAttribute(IS_BACKGROUND_USER);
	}
	
	public static void setBackgroudUser(boolean flag){
		ServletActionContext.getRequest().getSession().setAttribute(IS_BACKGROUND_USER,flag);
	}
	
	public static Sysopt getUser4Backgroud(){
		return (Sysopt)ServletActionContext.getRequest().getSession().getAttribute(USER);
	}
    /**
     * ip获取
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
	public static String getReqUrl(HttpServletRequest req){
		StringBuilder url = new StringBuilder();
		if(req.isSecure()){
			url.append("https://");
		}else{
			url.append("http://");
		}
		url.append(req.getServerName());  //服务器地址
		if(req.getServerPort()!=80){
			url.append(":").append(req.getServerPort());
		}
		url.append(req.getRequestURI());      //请求页面或其他地址  
        if(req.getQueryString()!=null){
        	url.append("?").append(req.getQueryString()); //参数  
        }
        return url.toString();
	}
	
	public static String getReqPreUrl(HttpServletRequest req){
		StringBuilder url = new StringBuilder();
		if(req.isSecure()){
			url.append("https://");
		}else if("sq.yahlj.com".equals(req.getServerName())){//临时使用把sq.yahlj.com的域名替换成https域名 wangk 2017-7-5 22:33:36
			url.append("https://");
		}else{
			url.append("http://");
		}
		url.append(req.getServerName());  //服务器地址
		if(req.getServerPort()!=80){
			url.append(":"+req.getServerPort());
		}
		if(req.getContextPath()!=null){
			url.append("/"+req.getContextPath());	
		}
        //log.info("the request pre url="+url);
        return url.toString();
	}
}
